package com.jymj.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jymj.entity.RenovatedFile;
import com.jymj.entity.dto.EnviorFileDto;
import com.jymj.entity.enviorFile.QueryParamDto;
import com.jymj.entity.fhtnty.EnviorFileFhEntity;
import com.jymj.entity.landmanage.PjEnviorFileEntity;
import com.jymj.service.EnviorFileService;
import com.jymj.service.EnviorSupvsService;
import com.jymj.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("EnviorFile")
public class EnviorFileController extends AbstractController {
    @Autowired
    private EnviorFileService enviorFileService;
    @Autowired
    private EnviorSupvsService enviorSupvsService;

    private final String SAVE_PATH = "enviorFile";


    @PostMapping("/queryPicByMonth")
    public R queryPicByMonth(@RequestBody QueryParamDto queryParamDto) throws Exception {
        String downloadPath = enviorSupvsService.getXzqmcByDate(queryParamDto);
        return R.ok().put("data", downloadPath);
    }


    //自行改sql下载图片
    @PostMapping("/quertFile7")
    public void quertFile7(){
        enviorSupvsService.quertFile7();
    }

    /*
     * 按村查询点位图片 压缩
     * */
//    @RequestMapping(value = "/queryAllPic",method = RequestMethod.POST)
//    public R queryAllPic(@RequestBody Map map,HttpServletRequest request, HttpServletResponse response) throws Exception {
//
//        String date = map.get("date") == null ? null : map.get("date").toString();
//        String code = map.get("code") == null ? null : map.get("code").toString();
//        Integer type = map.get("type") == null ? null : Integer.valueOf(map.get("type").toString());
//        ArrayList list1 = new ArrayList();
//        Integer[] hjzzsjs = null;
//        if(map.containsKey("hjzzsjs")  && map.get("hjzzsjs") != null){
//            String codes  = map.get("hjzzsjs").toString();
//            String i = codes.substring(1,codes.length()-1);
//            String str= i.replace("\"", "");
//            list1 = new ArrayList(Arrays.asList(str.split(",")));
//            if (list1.size() > 0 &&! list1.get(0).equals("")){
//                hjzzsjs = Arrays.stream(list1.toArray(new String[list1.size()])).map(p ->
//                        Integer.valueOf(p.toString().trim())).toArray(Integer[]::new);
//            }
//        }
//
//        //查询行政区
//        List<PjEnviorSupvsEntity> pjEnviorSupvsEntities = enviorSupvsService.queryByXzqmc(date,code,type,hjzzsjs);
//
//        if (pjEnviorSupvsEntities == null || pjEnviorSupvsEntities.size() == 0){
//            return R.error("暂无数据");
//        }
//        //按村获取图片
//        File genPath=new File(ResourceUtils.getURL("jar:").getPath());
//        String savePath1=genPath.getAbsolutePath().replace("jar:","fileupload");
//        String[] strings ={};
//        CopyFileByChannel.deleteFolder(new File(savePath1 + File.separator + Copy_PATH));
//        //String savePath1 = "E:\\jymj\\hjs\\tz-hjs\\target\\classes\\fileupload";
//        List<PjEnviorFileEntity> pjEnviorFileEntities = new ArrayList<>();
//        for (PjEnviorSupvsEntity enviorSupvsEntity:pjEnviorSupvsEntities){
//            //查询村内外
//            List<Integer> list = enviorFileService.queryCnw(date,enviorSupvsEntity.getCode());
//            for (Integer integer : list) {
//                String cnw = CnwEnum.getName(integer);
//                //查询类型
//                List<Integer> lists = enviorFileService.queryHjzzsj(date,enviorSupvsEntity.getCode(),integer,type,hjzzsjs);
//                for (Integer i : lists){
//                    //查询图片
//                    pjEnviorFileEntities =
//                            enviorFileService.queryAllPic(date,enviorSupvsEntity.getCode(),i,integer,hjzzsjs,type);
//                    //拼接路径 按村压缩文件
//                    System.out.println(i);
//                    String hjzzsjtext = HjzzsjEnum.getName(i);
//                    for (PjEnviorFileEntity enviorFileEntity : pjEnviorFileEntities){
//                        File copytPath = new File(savePath1 + File.separator
//                                + Copy_PATH + File.separator + enviorSupvsEntity.getXzqmc() + File.separator
//                                + cnw + File.separator + hjzzsjtext);
//                        //查找到文件 放文件夹
//                        if(!copytPath.exists()) {
//                            copytPath.mkdirs();
//                        }
//                        CopyFileByChannel.copy(new File(savePath1 + File.separator
//                                + enviorFileEntity.getPath()),copytPath );
//
//                    }
//                }
//            }
//            //加文件夹放一起
//            strings = insert(strings,savePath1 + File.separator
//                    + Copy_PATH + File.separator + enviorSupvsEntity.getXzqmc());
//        }
//
//
//        //进行文件压缩
//        String zippath = savePath1 + File.separator + Zip_PATH;
//        File file = new File(zippath);
//        //创建zip文件夹
//        if(!file.exists()) {
//            file.mkdirs();
//        }
//
//        //多文件夹压缩
//        CopyFileByChannel.zipfile(strings,zippath+File.separator +"copy.zip");
//        //删除复制文件
//        CopyFileByChannel.deleteFolder(new File(savePath1 + File.separator + Copy_PATH));
//        return R.ok().put("data",Zip_PATH+File.separator +"copy.zip");
//    }

    /*
     * 查询聚合图片  type 1 区  2 镇  3 村  4 最小
     * */
    @RequestMapping("/queryList")
    public R queryList(EnviorFileDto enviorFileDto) {
        List<EnviorFileFhEntity> enviorFileFhEntity = null;
        if (enviorFileDto.getType() != null && enviorFileDto.getType() == 1) {
            //查询区的图片数量
            enviorFileFhEntity = enviorFileService.queryListByType1(enviorFileDto);
        } else if (enviorFileDto.getType() != null && enviorFileDto.getType() == 2) {
            //查询镇的图片数量
            enviorFileFhEntity = enviorFileService.queryListByType2(enviorFileDto);
        } else if (enviorFileDto.getType() != null && enviorFileDto.getType() == 3) {
            //查询村的图片数量
            enviorFileFhEntity = enviorFileService.queryListByType3(enviorFileDto);
        } else {
            //查询图片数量
            enviorFileFhEntity = enviorFileService.queryListByType(enviorFileDto);
        }
        return R.ok().put("data", enviorFileFhEntity);
    }

    /*
     * 查看图片详情
     * */
    @RequestMapping("/info")
    public R queryInfo(EnviorFileDto enviorFileDto) {
        PageHelper.startPage(enviorFileDto.getPage(), enviorFileDto.getLimit());
        List<PjEnviorFileEntity> pjEnviorFileEntities = enviorFileService.queryList(enviorFileDto);
        PageInfo<PjEnviorFileEntity> pjEnviorFileEntityPageInfo = new PageInfo<>(pjEnviorFileEntities);
        return R.ok().put("data", pjEnviorFileEntityPageInfo);
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public R delete(@RequestBody Integer id, HttpServletRequest request) throws FileNotFoundException {
        if (id == null) {
            return R.ok();
        }
        File genPath = new File(ResourceUtils.getURL("jar:").getPath());
        File savePath1 = new File(genPath.getAbsolutePath().replace("jar:", "fileupload"));
        PjEnviorFileEntity pjEnviorFileEntity = enviorFileService.queryObject(id);
        if (pjEnviorFileEntity == null) {
            return R.ok();
        }
        File file = new File(savePath1 + File.separator + pjEnviorFileEntity.getPath());
        if (file.exists()) {
            file.delete();
        }
        enviorFileService.delete(id);
        return R.ok("删除成功");
    }

    /**
     * 上传图片
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public R uploadData(HttpServletRequest request) throws FileNotFoundException {
        //资料表实体
        PjEnviorFileEntity pjEnviorFileEntity = new PjEnviorFileEntity();
        // 获取根目录的绝对路径
        File genPath = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!genPath.exists()) {
            genPath = new File("");
        }
        //在开发测试模式时，得到地址为：{项目跟目录}/target/progress/
        //在打成jar正式发布时，得到的地址为:{发布jar包目录}/progress/
        File savePath = new File(genPath.getAbsolutePath(), "fileupload" + File.separator + SAVE_PATH);
        File savePath1 = new File(genPath.getAbsolutePath(), "fileupload");
        if (!savePath.exists()) {
            savePath.mkdirs();
            logger.info("文件路径为：+" + savePath.getAbsolutePath() );
        }
        //if (multipartResolver.isMultipart(request)) {
        //转换成多部分request
        MultipartHttpServletRequest multiRequest = null;
        if (request instanceof MultipartHttpServletRequest) {
            multiRequest = (MultipartHttpServletRequest) (request);
        } else {
            return R.error("文件不能为空！");
        }
        String msid = multiRequest.getParameter("msid");
        String filetype = multiRequest.getParameter("filetype");
        Integer type = Integer.valueOf(multiRequest.getParameter("type") == null ?
                "1" : multiRequest.getParameter("type"));
        //取得request中的所有文件名
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            //取得上传文件
            MultipartFile file = multiRequest.getFile(iter.next());
            if (file != null && file.getSize() > 0) {
                Integer msid1 = Integer.parseInt(msid);
                Integer filetype1 = Integer.parseInt(filetype);
                //取得当前上传文件的文件名称
                String myFileName = file.getOriginalFilename();
                //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                if (!"".equals(myFileName.trim())) {
                    //重命名上传后的文件名
                    String fileName = file.getOriginalFilename();
                    String ext = fileName.substring(fileName.indexOf("."));
                    TimeString st = new TimeString();
                    pjEnviorFileEntity.setPath(SAVE_PATH + File.separator + st.getTimeString() + ext);
                    pjEnviorFileEntity.setName(fileName);
                    pjEnviorFileEntity.setMsid(msid1);
                    pjEnviorFileEntity.setFiletype(filetype1);
                    pjEnviorFileEntity.setType(type);
                    pjEnviorFileEntity.setEntime(new Date());
                    pjEnviorFileEntity.setEnpsn(Integer.parseInt(getUserId().toString()));
                    enviorFileService.save(pjEnviorFileEntity);

                    //上传路径
                    String path = savePath1 + File.separator + pjEnviorFileEntity.getPath();
                    File localFile = new File(path);
                    try {
                        file.transferTo(localFile);
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                        throw new RRException("图片上传失败");
                    }
                }
            } else {
                throw new RRException("图片上传失败");
            }
        }
        //}
        return R.ok().put("data", pjEnviorFileEntity);
    }


    //往字符串数组追加新数据
    private static String[] insert(String[] arr, String str) {
        int size = arr.length;  //获取数组长度
        String[] tmp = new String[size + 1];  //新建临时字符串数组，在原来基础上长度加一
        for (int i = 0; i < size; i++) {  //先遍历将原来的字符串数组数据添加到临时字符串数组
            tmp[i] = arr[i];
        }
        tmp[size] = str;  //在最后添加上需要追加的数据
        return tmp;  //返回拼接完成的字符串数组
    }

    /**
     * 添加固定点位图片
     * @param file
     * @param type  1编号照片 2点位照片
     * @return
     */
    @PostMapping("/uploadPointFile")
    public R uploadPointFile(MultipartFile file,Integer type){
        RenovatedFile renovatedFile = enviorFileService.uploadPointFile(file,type);
        return R.ok().put("data", renovatedFile);
    }
    @PostMapping("/deletePointFile")
    public R deletePointFile(@RequestBody Long... ids){
        enviorFileService.deletePointFile(ids);
        return R.ok("删除成功");
    }

}
